import { PageContainer } from '@ant-design/pro-components';
import React, { useEffect, useState } from 'react';
import { Card, Form, Input, Button, message, Select, Tag, Row, Col, Spin, Upload, Modal, Image } from 'antd';
import { useNavigate, useLocation } from 'react-router-dom';
import { createStyles } from 'antd-style';
import { UploadOutlined } from '@ant-design/icons';
import type { UploadFile } from 'antd/es/upload/interface';
import { apiUpdate, apiDetail, apipage, uploadFile } from '@/services/system/apimanage';
import { useModel } from '@umijs/max';
import CustomPageContainer from '@/components/CustomPageContainer';
import { getToken } from '@/utils/auth';

const { Option } = Select;

const useStyles = createStyles(({ token }) => ({
  container: {
    padding: '24px',
    background: '#f5f5f5',
    minHeight: 'calc(100vh - 48px)',
  },
  card: {
    borderRadius: '8px',
    boxShadow: '0 1px 2px 0 rgba(0, 0, 0, 0.03)',
  },
  header: {
    backgroundColor: '#1890ff',
    color: 'white',
    padding: '10px',
    textAlign: 'center',
    fontSize: '16px',
    fontWeight: 'bold',
  },
  form: {
    margin: '0 auto',
  },
  formSection: {
    borderBottom: '1px solid #f0f0f0',
    padding: '16px 0',
  },
  label: {
    textAlign: 'right',
    paddingRight: '12px',
    lineHeight: '32px',
  },
  buttonGroup: {
    display: 'flex',
    justifyContent: 'center',
    gap: '16px',
    marginTop: '20px',
  },
  title: {
    fontSize: '16px',
    fontWeight: 'bold',
    color: '#1890ff',
    borderBottom: '2px solid #1890ff',
    paddingBottom: '8px',
    marginBottom: '24px',
  },
  uploadButton: {
    width: '100%',
  },
  previewText: {
    marginLeft: '8px',
    color: token.colorPrimary,
    cursor: 'pointer',
  },
}));

// 证件类型选项
const cardTypeOptions = [
  { label: '身份证', value: '1' },
  { label: '港澳台身份证', value: '2' },
  { label: '护照', value: '3' },
];

const ApiManageEdit: React.FC = () => {
  const { styles } = useStyles();
  const [form] = Form.useForm();
  const navigate = useNavigate();
  const location = useLocation();
  const record = location.state?.record || {};
  const { initialState } = useModel('@@initialState');
  const { institutionId } = useModel('auth');
  const [loading, setLoading] = useState(false);

  // 文件上传状态管理
  const [cardFront, setCardFront] = useState<UploadFile[]>([]);
  const [cardBehind, setCardBehind] = useState<UploadFile[]>([]);
  const [adminCardFront, setAdminCardFront] = useState<UploadFile[]>([]);
  const [adminCardBehind, setAdminCardBehind] = useState<UploadFile[]>([]);
  const [legalRepresentativePhoto, setLegalRepresentativePhoto] = useState<UploadFile[]>([]);
  const [delectronicSignatureAuthentication, setDelectronicSignatureAuthentication] = useState<UploadFile[]>([]);
  const [registrationServiceAgreement, setRegistrationServiceAgreement] = useState<UploadFile[]>([]);
  const [institutionNameID, setInstitutionNameID] = useState('');
  const [institutionList, setInstitutionList] = useState<any[]>([]);
  const [institutionLoading, setInstitutionLoading] = useState(false);

  // 文件预览状态
  const [previewOpen, setPreviewOpen] = useState(false);
  const [previewImage, setPreviewImage] = useState('');
  const [previewTitle, setPreviewTitle] = useState('');

  // 获取机构列表
  useEffect(() => {
    fetchInstitutionList();
  }, []);

  const fetchInstitutionList = async () => {
    try {
      setInstitutionLoading(true);
      const response = await apipage({
        institutionId,
      });

      if (response.code === 200 && response.data) {
        console.log('机构列表数据:', response.data);
        const institutionData = Array.isArray(response.data) ? response.data : [];
        setInstitutionList(institutionData);
      } else {
        message.error(response.msg || '获取上级机构列表失败');
        setInstitutionList([]);
      }
    } catch (error) {
      console.error('获取上级机构列表错误:', error);
      message.error('获取上级机构列表失败');
      setInstitutionList([]);
    } finally {
      setInstitutionLoading(false);
    }
  };

  // 获取详情数据
  useEffect(() => {
    if (record.institutionId) {
      fetchDetail();
    }
  }, [record.institutionId]);

  const fetchDetail = async () => {
    console.log('record', record);
    try {
      setLoading(true);
      const response = await apiDetail({
        institutionId: record.institutionId,
        institutionRoleId: record.institutionRoleId
      });

      if (response.code === 200 && response.data) {
        console.log('机构详情数据:', response.data);
        setInstitutionNameID(response.data.institutionId);
        // 设置表单数据
        form.setFieldsValue(response.data);

        // 设置文件数据
        if (response.data.cardFront) {
          setCardFront([
            {
              uid: '-1',
              name: '法人证件正面',
              status: 'done',
              url: response.data.cardFront,
              response: { url: response.data.cardFront }
            }
          ]);
        }

        if (response.data.cardBehind) {
          setCardBehind([
            {
              uid: '-2',
              name: '法人证件反面',
              status: 'done',
              url: response.data.cardBehind,
              response: { url: response.data.cardBehind }
            }
          ]);
        }

        if (response.data.adminCardFront) {
          setAdminCardFront([
            {
              uid: '-3',
              name: '管理员证件正面',
              status: 'done',
              url: response.data.adminCardFront,
              response: { url: response.data.adminCardFront }
            }
          ]);
        }

        if (response.data.adminCardBehind) {
          setAdminCardBehind([
            {
              uid: '-4',
              name: '管理员证件反面',
              status: 'done',
              url: response.data.adminCardBehind,
              response: { url: response.data.adminCardBehind }
            }
          ]);
        }

        if (response.data.legalRepresentativePhoto) {
          setLegalRepresentativePhoto([
            {
              uid: '-5',
              name: '法人授权委托书',
              status: 'done',
              url: response.data.legalRepresentativePhoto,
              response: { url: response.data.legalRepresentativePhoto }
            }
          ]);
        }

        if (response.data.delectronicSignatureAuthentication) {
          setDelectronicSignatureAuthentication([
            {
              uid: '-6',
              name: '电子签名授权认证委托书',
              status: 'done',
              url: response.data.delectronicSignatureAuthentication,
              response: { url: response.data.delectronicSignatureAuthentication }
            }
          ]);
        }

        if (response.data.registrationServiceAgreement) {
          setRegistrationServiceAgreement([
            {
              uid: '-7',
              name: '用户注册与服务协议',
              status: 'done',
              url: response.data.registrationServiceAgreement,
              response: { url: response.data.registrationServiceAgreement }
            }
          ]);
        }
      } else {
        message.error(response.msg || '获取机构详情失败');
      }
    } catch (error) {
      console.error('获取机构详情失败:', error);
      message.error('获取机构详情失败');
    } finally {
      setLoading(false);
    }
  };

  const onFinish = async (values: any) => {
    try {
      setLoading(true);

      // 整合表单数据
      const formData = {
        ...values,
        id: record.id, // 确保包含ID
        fatherInstitutionId: institutionId,
        institutionId: institutionNameID,
        authenticationStatus: 1, // 已认证
        status: 0, // 正常
        // 文件上传字段
        cardFront: cardFront[0]?.response?.url || '',
        cardBehind: cardBehind[0]?.response?.url || '',
        adminCardFront: adminCardFront[0]?.response?.url || '',
        adminCardBehind: adminCardBehind[0]?.response?.url || '',
        legalRepresentativePhoto: legalRepresentativePhoto[0]?.response?.url || '',
        delectronicSignatureAuthentication: delectronicSignatureAuthentication[0]?.response?.url || '',
        registrationServiceAgreement: registrationServiceAgreement[0]?.response?.url || '',
      };

      console.log('提交的表单数据:', formData);
      const response = await apiUpdate(formData);
      if (response.code === 200) {
        message.success('更新机构成功');
        navigate('/system/apimanage');
      } else {
        message.error(response.msg || '更新机构失败');
      }
    } catch (error) {
      console.error('提交失败:', error);
      message.error('更新机构失败');
    } finally {
      setLoading(false);
    }
  };

  const handlePreview = async (file: UploadFile) => {
    if (!file.url && !file.preview) {
      file.preview = file.url || file.response?.url;
    }

    const fileUrl = file.url || file.response?.url || '';
    const fileType = fileUrl.toLowerCase().split('.').pop();

    setPreviewImage(fileUrl);
    setPreviewOpen(true);
    setPreviewTitle(file.name || fileUrl.substring(fileUrl.lastIndexOf('/') + 1));
  };

  const handleCancel = () => {
    navigate('/system/apimanage');
  };

  const handlePreviewCancel = () => {
    setPreviewOpen(false);
  };

  // 自定义上传方法
  const customUpload = async (options: any) => {
    const { file, onSuccess, onError, onProgress } = options;

    try {
      onProgress({ percent: 0 });
      const response = await uploadFile(file);

      console.log('上传响应:', response);

      if (response.code === 200 && response.data) {
        onProgress({ percent: 100 });
        onSuccess({ url: response.data });
        message.success('上传成功');
      } else {
        onError(new Error(response.msg || '上传失败'));
        message.error(response.msg || '上传失败');
      }
    } catch (error) {
      console.error('上传错误:', error);
      onError(error);
      message.error('上传失败');
    }
  };

  // 文件上传配置
  const uploadProps = {
    maxCount: 1,
    accept: 'image/*,.pdf',
    customRequest: customUpload,
    onPreview: handlePreview,
    showUploadList: {
      showPreviewIcon: true,
      showRemoveIcon: true,
    },
  };

  return (
    <CustomPageContainer>
      <div className={styles.container}>
        <Card className={styles.card}>
          <div className={styles.title}>机构修改</div>
          <Spin spinning={loading}>
            <Form
              form={form}
              layout="vertical"
              onFinish={onFinish}
              className={styles.form}
              initialValues={{
                cardType: '1',
                adminCardType: '1'
              }}
            >
              <div className={styles.formSection}>
                <Row gutter={[24, 16]}>
                  <Col span={12}>
                    <Row>
                      <Col span={8} className={styles.label}>机构名称：</Col>
                      <Col span={16}>
                        <Form.Item
                          name="institutionName"
                          rules={[{ required: true, message: '请输入机构名称' }]}
                          noStyle
                        >
                          <Input placeholder="请输入机构名称" />
                        </Form.Item>
                      </Col>
                    </Row>
                  </Col>
                  <Col span={12}>
                    <Row>
                      <Col span={8} className={styles.label}>机构角色：</Col>
                      <Col span={16}>
                        <Form.Item
                          name="institutionRoleId"
                          rules={[{ required: true, message: '请选择机构角色' }]}
                          noStyle
                        >
                           <Select placeholder="请选择机构角色" >
                            <Option value="01">平台</Option>
                            <Option value="02">公开市场</Option>
                            <Option value="03">交易会员</Option>
                            <Option value="04">核心企业(保留)</Option>
                            <Option value="05">资金方</Option>
                            <Option value="06">担保方</Option>
                            <Option value="07">仓储方</Option>
                            <Option value="08">物流方</Option>
                            <Option value="99">技术支持方</Option>
                          </Select>
                        </Form.Item>
                      </Col>
                    </Row>
                  </Col>

                  <Col span={12}>
                    <Row>
                      <Col span={8} className={styles.label}>账户名：</Col>
                      <Col span={16}>
                        <Form.Item
                          name="accountName"
                          rules={[{ required: true, message: '请输入账户名' }]}
                          noStyle
                        >
                          <Input placeholder="请输入账户名" />
                        </Form.Item>
                      </Col>
                    </Row>
                  </Col>
                  <Col span={12}>
                    <Row>
                      <Col span={8} className={styles.label}>开户行：</Col>
                      <Col span={16}>
                        <Form.Item
                          name="bank"
                          rules={[{ required: true, message: '请输入开户行' }]}
                          noStyle
                        >
                          <Input placeholder="请输入开户行" />
                        </Form.Item>
                      </Col>
                    </Row>
                  </Col>

                  <Col span={12}>
                    <Row>
                      <Col span={8} className={styles.label}>统一社会信用代码：</Col>
                      <Col span={16}>
                        <Form.Item
                          name="creditCode"
                          rules={[{ required: true, message: '请输入统一社会信用代码' }]}
                          noStyle
                        >
                          <Input placeholder="请输入统一社会信用代码" />
                        </Form.Item>
                      </Col>
                    </Row>
                  </Col>
                  <Col span={12}>
                    <Row>
                      <Col span={8} className={styles.label}>认证状态：</Col>
                      <Col span={16}>
                        <Tag color="success">已认证</Tag>
                      </Col>
                    </Row>
                  </Col>

                  <Col span={12}>
                    <Row>
                      <Col span={8} className={styles.label}>总授信额度：</Col>
                      <Col span={16}>
                        <Form.Item
                          name="allCreditLimit"
                          rules={[{ required: true, message: '请输入总授信额度' }]}
                          noStyle
                        >
                          <Input addonAfter="元" placeholder="请输入总授信额度" />
                        </Form.Item>
                      </Col>
                    </Row>
                  </Col>
                  <Col span={12}>
                    <Row>
                      <Col span={8} className={styles.label}>可用授信额度：</Col>
                      <Col span={16}>
                        <Form.Item
                          name="creditLimit"
                          rules={[{ required: true, message: '请输入可用授信额度' }]}
                          noStyle
                        >
                          <Input addonAfter="元" placeholder="请输入可用授信额度" />
                        </Form.Item>
                      </Col>
                    </Row>
                  </Col>

                  <Col span={12}>
                    <Row>
                      <Col span={8} className={styles.label}>注册地址：</Col>
                      <Col span={16}>
                        <Form.Item
                          name="address"
                          rules={[{ required: true, message: '请输入注册地址' }]}
                          noStyle
                        >
                          <Input placeholder="请输入注册地址" />
                        </Form.Item>
                      </Col>
                    </Row>
                  </Col>
                </Row>
              </div>

              <Row gutter={24}>
                <Col span={12}>
                  <div className={styles.formSection}>
                    <Row gutter={[24, 16]}>
                      <Col span={24}>
                        <Row>
                          <Col span={8} className={styles.label}>法人代表：</Col>
                          <Col span={16}>
                            <Form.Item
                              name="legalRepresentative"
                              rules={[{ required: true, message: '请输入法人代表' }]}
                              noStyle
                            >
                              <Input placeholder="请输入法人代表" />
                            </Form.Item>
                          </Col>
                        </Row>
                      </Col>
                      <Col span={24}>
                        <Row>
                          <Col span={8} className={styles.label}>法人手机号：</Col>
                          <Col span={16}>
                            <Form.Item
                              name="legalRepresentativePhone"
                              rules={[{ required: true, message: '请输入法人手机号' }]}
                              noStyle
                            >
                              <Input placeholder="请输入法人手机号" />
                            </Form.Item>
                          </Col>
                        </Row>
                      </Col>
                      <Col span={24}>
                        <Row>
                          <Col span={8} className={styles.label}>法人证件类型：</Col>
                          <Col span={16}>
                            <Form.Item
                              name="cardType"
                              rules={[{ required: true, message: '请选择法人证件类型' }]}
                              noStyle
                            >
                              <Select>
                                {cardTypeOptions.map(option => (
                                  <Option key={option.value} value={option.value}>
                                    {option.label}
                                  </Option>
                                ))}
                              </Select>
                            </Form.Item>
                          </Col>
                        </Row>
                      </Col>
                      <Col span={24}>
                        <Row>
                          <Col span={8} className={styles.label}>法人证件号码：</Col>
                          <Col span={16}>
                            <Form.Item
                              name="cardNumber"
                              rules={[{ required: true, message: '请输入法人证件号码' }]}
                              noStyle
                            >
                              <Input placeholder="请输入法人证件号码" />
                            </Form.Item>
                          </Col>
                        </Row>
                      </Col>
                      <Col span={24}>
                        <Row>
                          <Col span={8} className={styles.label}>法人证件正面：</Col>
                          <Col span={16}>
                            <Form.Item
                              name="cardFront"
                              rules={[{ required: true, message: '请上传法人证件正面照片' }]}
                              noStyle
                            >
                              <Upload
                                {...uploadProps}
                                fileList={cardFront}
                                onChange={({ fileList }) => setCardFront(fileList)}
                              >
                                <Button icon={<UploadOutlined />}>上传</Button>
                                <span
                                  className={styles.previewText}
                                  onClick={() => {
                                    if (cardFront[0]) {
                                      handlePreview(cardFront[0]);
                                    }
                                  }}
                                >

                                </span>
                              </Upload>
                            </Form.Item>
                          </Col>
                        </Row>
                      </Col>
                      <Col span={24}>
                        <Row>
                          <Col span={8} className={styles.label}>法人证件反面：</Col>
                          <Col span={16}>
                            <Form.Item
                              name="cardBehind"
                              rules={[{ required: true, message: '请上传法人证件反面照片' }]}
                              noStyle
                            >
                              <Upload
                                {...uploadProps}
                                fileList={cardBehind}
                                onChange={({ fileList }) => setCardBehind(fileList)}
                              >
                                <Button icon={<UploadOutlined />}>上传</Button>
                                <span
                                  className={styles.previewText}
                                  onClick={() => {
                                    if (cardBehind[0]) {
                                      handlePreview(cardBehind[0]);
                                    }
                                  }}
                                >

                                </span>
                              </Upload>
                            </Form.Item>
                          </Col>
                        </Row>
                      </Col>
                    </Row>
                  </div>
                </Col>

                <Col span={12}>
                  <div className={styles.formSection}>
                    <Row gutter={[24, 16]}>
                      <Col span={24}>
                        <Row>
                          <Col span={8} className={styles.label}>管理员：</Col>
                          <Col span={16}>
                            <Form.Item
                              name="adminName"
                              rules={[{ required: true, message: '请输入管理员' }]}
                              noStyle
                            >
                              <Input placeholder="请输入管理员" />
                            </Form.Item>
                          </Col>
                        </Row>
                      </Col>
                      <Col span={24}>
                        <Row>
                          <Col span={8} className={styles.label}>管理员用户名：</Col>
                          <Col span={16}>
                            <Form.Item
                              name="adminUserName"
                              rules={[{ required: true, message: '请输入管理员用户名' }]}
                              noStyle
                            >
                              <Input placeholder="请输入管理员用户名" />
                            </Form.Item>
                          </Col>
                        </Row>
                      </Col>
                      <Col span={24}>
                        <Row>
                          <Col span={8} className={styles.label}>管理员手机号：</Col>
                          <Col span={16}>
                            <Form.Item
                              name="adminPhone"
                              rules={[{ required: true, message: '请输入管理员手机号' }]}
                              noStyle
                            >
                              <Input placeholder="请输入管理员手机号" />
                            </Form.Item>
                          </Col>
                        </Row>
                      </Col>
                      <Col span={24}>
                        <Row>
                          <Col span={8} className={styles.label}>管理员证件类型：</Col>
                          <Col span={16}>
                            <Form.Item
                              name="adminCardType"
                              rules={[{ required: true, message: '请选择管理员证件类型' }]}
                              noStyle
                            >
                              <Select>
                                {cardTypeOptions.map(option => (
                                  <Option key={option.value} value={option.value}>
                                    {option.label}
                                  </Option>
                                ))}
                              </Select>
                            </Form.Item>
                          </Col>
                        </Row>
                      </Col>
                      <Col span={24}>
                        <Row>
                          <Col span={8} className={styles.label}>管理员证件号码：</Col>
                          <Col span={16}>
                            <Form.Item
                              name="adminCardNumber"
                              rules={[{ required: true, message: '请输入管理员证件号码' }]}
                              noStyle
                            >
                              <Input placeholder="请输入管理员证件号码" />
                            </Form.Item>
                          </Col>
                        </Row>
                      </Col>
                      <Col span={24}>
                        <Row>
                          <Col span={8} className={styles.label}>管理员证件正面：</Col>
                          <Col span={16}>
                            <Form.Item
                              name="adminCardFront"
                              rules={[{ required: true, message: '请上传管理员证件正面照片' }]}
                              noStyle
                            >
                              <Upload
                                {...uploadProps}
                                fileList={adminCardFront}
                                onChange={({ fileList }) => setAdminCardFront(fileList)}
                              >
                                <Button icon={<UploadOutlined />}>上传</Button>
                                <span
                                  className={styles.previewText}
                                  onClick={() => {
                                    if (adminCardFront[0]) {
                                      handlePreview(adminCardFront[0]);
                                    }
                                  }}
                                >

                                </span>
                              </Upload>
                            </Form.Item>
                          </Col>
                        </Row>
                      </Col>
                      <Col span={24}>
                        <Row>
                          <Col span={8} className={styles.label}>管理员证件反面：</Col>
                          <Col span={16}>
                            <Form.Item
                              name="adminCardBehind"
                              rules={[{ required: true, message: '请上传管理员证件反面照片' }]}
                              noStyle
                            >
                              <Upload
                                {...uploadProps}
                                fileList={adminCardBehind}
                                onChange={({ fileList }) => setAdminCardBehind(fileList)}
                              >
                                <Button icon={<UploadOutlined />}>上传</Button>
                                <span
                                  className={styles.previewText}
                                  onClick={() => {
                                    if (adminCardBehind[0]) {
                                      handlePreview(adminCardBehind[0]);
                                    }
                                  }}
                                >

                                </span>
                              </Upload>
                            </Form.Item>
                          </Col>
                        </Row>
                      </Col>
                    </Row>
                  </div>
                </Col>
              </Row>

              <div className={styles.formSection}>
                <Row gutter={[24, 16]}>
                  <Col span={24}>
                    <Row>
                      <Col span={4} className={styles.label}>法人授权委托书：</Col>
                      <Col span={20}>
                        <Upload
                          {...uploadProps}
                          fileList={legalRepresentativePhoto}
                          onChange={({ fileList }) => setLegalRepresentativePhoto(fileList)}
                        >
                          <Button icon={<UploadOutlined />}>上传</Button>
                          <span
                            className={styles.previewText}
                            onClick={() => {
                              if (legalRepresentativePhoto[0]) {
                                handlePreview(legalRepresentativePhoto[0]);
                              }
                            }}
                          >

                          </span>
                        </Upload>
                      </Col>
                    </Row>
                  </Col>
                  <Col span={24}>
                    <Row>
                      <Col span={4} className={styles.label}>电子签名授权认证委托书：</Col>
                      <Col span={20}>
                        <Upload
                          {...uploadProps}
                          fileList={delectronicSignatureAuthentication}
                          onChange={({ fileList }) => setDelectronicSignatureAuthentication(fileList)}
                        >
                          <Button icon={<UploadOutlined />}>上传</Button>
                          <span
                            className={styles.previewText}
                            onClick={() => {
                              if (delectronicSignatureAuthentication[0]) {
                                handlePreview(delectronicSignatureAuthentication[0]);
                              }
                            }}
                          >
                          </span>
                        </Upload>
                      </Col>
                    </Row>
                  </Col>
                  <Col span={24}>
                    <Row>
                      <Col span={4} className={styles.label}>用户注册与服务协议：</Col>
                      <Col span={20}>
                        <Upload
                          {...uploadProps}
                          fileList={registrationServiceAgreement}
                          onChange={({ fileList }) => setRegistrationServiceAgreement(fileList)}
                        >
                          <Button icon={<UploadOutlined />}>上传</Button>
                          <span
                            className={styles.previewText}
                            onClick={() => {
                              if (registrationServiceAgreement[0]) {
                                handlePreview(registrationServiceAgreement[0]);
                              }
                            }}
                          >

                          </span>
                        </Upload>
                      </Col>
                    </Row>
                  </Col>
                </Row>
              </div>

              <div className={styles.buttonGroup}>
                <Button type="primary" htmlType="submit">提交</Button>
                <Button onClick={handleCancel}>返回</Button>
              </div>
            </Form>
          </Spin>
        </Card>
      </div>

      {/* 添加预览弹窗 */}
      <Modal
        open={previewOpen}
        title={previewTitle}
        footer={null}
        onCancel={handlePreviewCancel}
      >
        {previewImage.toLowerCase().endsWith('.pdf') ? (
          <iframe
            src={previewImage}
            style={{ width: '100%', height: '500px' }}
            title={previewTitle}
          />
        ) : (
          <Image
            alt={previewTitle}
            style={{ width: '100%' }}
            src={previewImage}
          />
        )}
      </Modal>
    </CustomPageContainer>
  );
};

export default ApiManageEdit;
